package com.googlecode.utterlyidle.pdf;

import com.googlecode.utterlyidle.*;

import static java.lang.String.*;

public interface LinkRewriter {
    Response apply(Request request, Response response);

    public static class Defaults {

        public static LinkRewriter relativeToAbsolutePaths() {
            return new LinkRewriter() {
                @Override
                public Response apply(Request request, Response response) {
                    String protocol = request.headers().valueOption("X-Forwarded-Proto").getOrElse("http");
                    String host = request.headers().getValue("Host");
                    String prefix = format("%s://%s", protocol, host);
                    String value = response.entity().toString();
                    value = value.replaceAll("src=\"", "src=\"" + prefix);
                    value = value.replaceAll("src='", "src='" + prefix);
                    value = value.replaceAll("href=\"", "href=\"" + prefix);
                    value = value.replaceAll("href='", "href='" + prefix);
                    return ResponseBuilder.modify(response).entity(value).build();
                }
            };
        }

        public static LinkRewriter noOp() {
            return new LinkRewriter() {
                @Override
                public Response apply(Request request, Response response) {
                    return response;
                }
            };
        }
    }
}
